<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="addRoles">
      <el-row>
        <el-col class="addTop">
          <el-button type="primary" v-on:click="addRoles()">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData" border script style="width: 100%">
        <el-table-column type="expand">
          <!--展开权限-->
          <template slot-scope="scope">          
           <el-row v-for="(item1,itv) in scope.row.children" :key='item1.id' :class="itv==0?'botton_shol top_shol fiexCenter':'botton_shol fiexCenter'"> 
               <el-col :span="8">
                 <!--管理区-->
                <el-tag  closable @close="fixDelete(scope.row,item1.id,item1.authName)" :disable-transitions="false">                           
                 {{item1.authName}}
                 </el-tag><i class="el-icon-caret-right"></i>
               </el-col>
               <el-col :span="16">
                 <el-row v-for="(item2,itv2) in item1.children" :key='item2.id' :class="itv2==item1.children.length-1?'':'botton_shol'">
                   <!--二级管理区-->
                    <el-col :span="6"><el-tag @close="fixDelete(scope.row,item2.id,item2.authName)" :disable-transitions="false"  closable type='success' class='marto'>{{item2.authName}}</el-tag><i class="el-icon-caret-right"></i></el-col>
                    <el-col :span="18"><el-tag  @close="fixDelete(scope.row,item3.id,item3.authName)" :disable-transitions="false" closable type='warning' class='marto' v-for="item3 in item2.children" :key="item3.id">{{item3.authName}}</el-tag></el-col>          
                 </el-row>               
               </el-col>
           </el-row>
          </template>
          <!--权限的数据-->
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column prop="id" label="操作">
          <template slot-scope="scope">
            <el-row>
              <el-button
                type="primary"
                @click="edit(scope.row.id)"
                icon="el-icon-edit"
                size="small"
              >编辑</el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="Delet(scope.row.id)"
                size="small"
              >删除</el-button>
               <el-tooltip class="item" effect="dark" content="权限分配" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-star-off"
                @click="off(scope.row)"
                size="small"
              >分配权限</el-button>
               </el-tooltip>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--角色添加-->
    <el-dialog title="添加角色" :visible.sync="AddRolesVisible" width="50%" v-on:close="initRoles('ARoles')">
      <el-form ref="ARoles" :model="RoleAdd" label-width="80px" :rules="Addroles">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="RoleAdd.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="RoleAdd.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddRoles('ARoles')">确 定</el-button>
      </span>
    </el-dialog>

    <!--角色编辑-->
    <el-dialog title="用户编辑" :visible.sync="RolesVisible" width="50%">
      <el-form ref="Roles" :model="Roledata" label-width="80px" :rules="Rules">
        <el-form-item label="权力" prop="rolePermissionDesc">
          <el-input v-model="Roledata.rolePermissionDesc" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="Roledata.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="Roledata.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="UpdataOne">确 定</el-button>
      </span>
    </el-dialog>

    <!--权限分配-->
    <el-dialog
  title="提示"
  :visible.sync="RoledVisible" @close="clearRou"
  width="30%">
   <el-tree
  :data="rolset"
  show-checkbox
  node-key="id"
  :default-checked-keys="findId"
  :default-expand-all="true"
   ref="tree"
  :props="defaultProps">
</el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="RoledVisible = false">取 消</el-button>
    <el-button type="primary" @click="addOff()">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>

<script>
export default {
  created: async function() {
    this.Rolesinit();
    /*测试*/
  },
  name: "roles",
  data: () => {
    return {
      //初始化数据
      tableData: [],
      //添加角色
      RoleAdd: {
        roleName: "",
        roleDesc: ""
      },
      //添加角色的效验规则
      Addroles: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 6, message: "请输入最少3位数" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 6, max: 12, message: "请输入最少6位数" }
        ]
      },
      //添加角色框
      AddRolesVisible: false,
      //编辑角色的权限
      Roledata: {},
      //编辑角色的校验规则
      Rules: {
        roleName: [{ required: true, message: "请输入职位", trigger: "blur" }],
        roleDesc: [{ required: true, message: "请输入岗位", trigger: "blur" }]
      },
      //编辑角色弹框
      RolesVisible: false,
      //分配权限的弹框
      RoledVisible:false,
      //所有权限数据
      rolset:[],    
      //以什么属性为显示主标题
      defaultProps:{
         children: 'children',
         label:'authName'
      },
      //默认选中的id
      findId:[],
      //权限id（确定分配权限时存储位置）
      queryId:''
    };
  },
  methods: {
    //初始化函数
    async Rolesinit() {
      let { data: res } = await this.$http.get("/roles");
      if (res.meta.status != 200) {
        return this.$message.error("获取失败");
      }
      this.tableData = res.data;
      //console.log(res.data);
    },
    /*添加角色页面*/
    addRoles() {
      this.AddRolesVisible = true;
    },
    /*响应添加角色*/
    AddRoles(dom) {
      this.$refs[dom].validate(async item => {
        if (!item) {
          return this.$message.error("添加失败，该用户存在");
        }
        let { data: res } = await this.$http.post("/roles", this.RoleAdd);
        if (res.meta.status != 201) {
          return this.$message("添加失败");
        }
        this.initRoles(dom);
        this.$message.success("添加成功");
        this.Rolesinit();
        this.AddRolesVisible = false;
      });
    },
    /*表单重置*/
    initRoles(dom) {
      this.$refs[dom].resetFields();
    },
    /*编辑角色页面*/
    async edit(id) {
      this.RolesVisible = true;
      let { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status != 200) {
        return this.$message.error("用户请求失败");
      }
      this.Roledata = res.data;
      // console.log(this.Roledata);
    },
    /*角色编辑响应函数*/
    UpdataOne() {
      //双重验证，首先判断是否有空
      this.$refs.Roles.validate(async item => {
        if (item) {
          let { data: res } = await this.$http.put(
            "roles/" + this.Roledata.roleId,
            {
              roleName: this.Roledata.roleName,
              roleDesc: this.Roledata.roleDesc
            }
          );
          console.log(res);
          if (res.meta.status != 200) {
            return this.$message.error("编辑失败");
          }
          this.$message.success("编辑成功");
          //初始化
          this.Rolesinit();
          this.RolesVisible = false;
        } else {
          return this.$message.error("数据不能为空");
        }
      });
    },
    /*角色删除*/
    async Delet(id) {
      let red = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(item => item);
      console.log(red);
      if (red == "confirm") {
        let { data:res } = await this.$http.delete("roles/" + id);
        console.log(res);
        if (res.meta.status != "200") {
          return this.$message({ type: "info", message: "删除失败" });
        }
        this.$message.success("删除成功");
        this.Rolesinit();
      } else if (red == "cancel") {
        this.$message("取消删除");
      } else {
        return false;
      }
    },
    /*删除某个权限*/
    async fixDelete(RroleId, rightId,content) {
      //首先弹出是否删除该权限
       let a  = await this.$confirm('此操作将永久删除该权限, 是否继续?',content, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(item=>item);
      //点击是，发送ajax
      if(a=='confirm'){
        let { data:res } = await this.$http.delete(`roles/${RroleId.id}/rights/${rightId}`);
        if(res.meta.status!=200){
          return this.$message.error('删除权限失败')
          };
          //将最新的数据教给插槽
        RroleId.children = res.data;
        this.$message.success('删除权限成功');  
      }else{
        return this.$message('取消删除权限');
      }
    },
    /*/角色授权分配及渲染已有权*/
    async off(id) {
       this.queryId = id.id;
       //渲染所有的权限
       let {data:res} = await this.$http.get("rights/tree");
       if(res.meta.status!=200){
         console.log(res.meta);
         return this.$message.error('获取失败');
       }
       this.rolset = res.data;     
      //根据用户的选中当前用户已有的权限
       this.GetRouId(id,this.findId);
      this.RoledVisible = true;
    },
    //获取角色授权选中Id
    GetRouId(target,arr){
       if(!target.children){
         arr.push(target.id);
         return;
       };
       target.children.forEach((item)=>{
         this.GetRouId(item,this.findId);
       });
    },
    //每次关闭权限表时清空上次角色授权限存储选中的值
    clearRou(){
      this.findId = [];
    },
    /*授权分配*/
    async addOff(){
     // console.log('确定')
       //得到选中权限的数据
       console.log(this.$refs.tree.getHalfCheckedKeys());
      let abc = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys()
        ];
      abc = abc.join(',');
       //将数据发送到ajax请求
      let {data:res} = await this.$http.post(`roles/${this.queryId}/rights`,{rids:abc});    
      //判断是否成功
      if(res.meta.status!=200){
        console.log(res.meta);
        return this.$message.error('请求错误');
      }
      //提示成功
      this.$message.success('请求成功'); 
      //初始化函数
      this.Rolesinit();
       //关闭弹框
      this.RoledVisible = false;
    }
  }
};






/*
 //得到用户的选中的数据
      let abc = [...this.$refs.tree.getCheckedKeys(),...this.$refs.tree.getCheckedNodes()];
      abc = abc.join(',');
       console.log(abc);
      //发送ajax请求
     let {data:res} = await this.$http.post(`roles/${this.queryId}/rights`,{rids:abc});
      if(res.meta.status!=200){
        this.$message.error('授权失败');
        return;
      };
      this.$message.success('授权成功');
      //初始化函数
      this.Rolesinit();
      //关闭对话框
      this.RoledVisible = false;


 <el-tree ref="tree" :data="rolset" node-key="id" :default-checked-keys='findId' :props="defaultProps" show-checkbox :default-expand-all='true'></el-tree>

 //为后面的上交需要的id赋值
      this.queryId = id.id;
      //console.log(this.queryId);
      //取得权限数据
      let {data:res} = await this.$http.get('rights/tree');
      if(res.meta.status!=200){
        res.$message.error('获取权限失败');
      }
      this.$message.success('获取成功');
      //生成表单
      this.rolset = res.data;
       //取得用户的拥有的权限id值
       //根据id已有权限渲染到页面中
       this.GetRouId(id,this.findId);
       //显示对话框
       this.RoledVisible = true;
*/
//删除单一权限
/*let a = await this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(error => error);
      if (a == "confirm") {
        let { data: res } = await this.$http.delete(
          `roles/${RroleId.id}/rights/${rightId}`
        );
        if (res.meta.status != 200) {
          return this.$message.error("删除失败");
        }
        RroleId.children = res.data;
        //响应成功的话移除标签
        //this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
        this.$message.success("删除成功");
      } else {
        this.$message("取消删除");
      }*/




/* <template slot-scope="scope">
            <el-row
              v-for="(item,it) in scope.row.children"
              :key="item.id"
              :class="it==0?'fiexCenter botton_top botton_shol':'fiexCenter botton_shol'"
            >
              <el-col :span="8">
                <el-tag type="primary" plain size="small" closable @close="fixDelete(scope.row,item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="16">
                <el-row
                  v-for="(two,It) in item.children"
                  :key="two.id"
                  :class="It==item.children.length-1?'fiexCenter':'botton_shol fiexCenter'"
                >
                  <el-col :span="6" class="padd">
                    <el-tag
                      type="success"
                      plain
                      size="small"
                      closable
                      @close="fixDelete(scope.row,two.id)"
                    >{{two.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18" class="padd">
                    <el-tag
                      class="marto"
                      v-for="tag in two.children"
                      :key="tag.name"
                      closable
                      @close="fixDelete(scope.row,tag.id)"
                      size="small"
                      type="warning"
                    >{{tag.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>*/
</script>

<style scoped lang="less">
.addRoles {
  margin: 15px 0;
  .addTop {
    margin-bottom: 15px;
  }
  .botton_shol {
    border-bottom: 1px solid #eee;
  }
  .top_shol {
    border-top: 1px solid #eee;
  }
  .fiexCenter {
    display: flex;
    align-items: center;
  }
}
.marto {
  margin: 8px;
}
.leri {
  margin-left: 5px;
}
.padd {
  padding: 5px 15px;
}
</style>

